package uqbar.comm.netty;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import junit.framework.Assert;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

@Sharable
public class MockOutputHandler extends SimpleChannelHandler implements ChannelHandler {

	private OutputStream outputWriter;

	public MockOutputHandler(final OutputStream writer) {
		this.outputWriter = writer;
	}

	public MockOutputHandler() {
		this(new ByteArrayOutputStream());
	}

	@Override
	// Se llama con la respuesta
	public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
		ChannelBuffer buf = (ChannelBuffer) e.getMessage();

		while (buf.readable()) {
			int redeables = buf.readableBytes();
			buf.readBytes(this.outputWriter, redeables);
		}
	}

	public OutputStream getOutputWriter() {
		return this.outputWriter;
	}

	/**
	 * Asume que el output stream utilizado es un ByteArrayOutputStream,
	 * 
	 * @param message
	 * @param content
	 */
	public void assertContenido(final String message, final String content) {
		byte[] recibido = ((ByteArrayOutputStream) this.outputWriter).toByteArray();
		Assert.assertEquals(message, content, new String(recibido));
	}
}
